package cn.db.crawl.data.service;

import cn.db.crawl.data.download.ChromeHeadlessDownloader;
import cn.db.crawl.data.pipeline.AirAqiPipeline;
import cn.db.crawl.data.pipeline.AirDailyPipeline;
import cn.db.crawl.data.pipeline.BingImagePipeline;
import cn.db.crawl.data.processor.AirAqiProcessor;
import cn.db.crawl.data.processor.AirDailyProcessor;
import cn.db.crawl.data.processor.BingImageProcessor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.env.Environment;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import us.codecraft.webmagic.Spider;

/**
 * @author：zooooooooy
 * @date: 2023/10/26 - 16:52
 */
@Service
@RequiredArgsConstructor
public class ScheduleService implements DisposableBean, InitializingBean {

    @NonNull
    private AirDailyPipeline airDailyPipeline;

    @NonNull
    private AirAqiPipeline airAqiPipeline;

    @NonNull
    private BingImagePipeline bingImagePipeline;

    @NonNull
    private Environment environment;

    private ChromeHeadlessDownloader chromeHeadlessDownloader;

    private String cityId = "101200101";

    /**
     * 7日内天气
     */
    @Scheduled(cron = "0 0 10 * * ? ")
    public void air7Day() {
        // 7 days weather
        // wuhan weather
        Spider.create(new AirDailyProcessor(cityId)).addUrl("http://www.weather.com.cn/weather/"+ cityId +".shtml")
                .addPipeline(airDailyPipeline).run();
    }

    /**
     * 当天空气指数AQI
     */
    @Scheduled(cron = "0 0 10 * * ? ")
    public void airAqi() {
        // AQI
        Spider.create(new AirAqiProcessor(cityId)).addUrl("http://www.weather.com.cn/air/")
                .setDownloader(chromeHeadlessDownloader)
                .addPipeline(airAqiPipeline).run();
    }

    /**
     * 获取bing背景图片
     */
    @Scheduled(cron = "0 0 10 * * ? ")
    public void bingImage() {
        // Bing image crawl
        Spider.create(new BingImageProcessor()).addUrl("https://cn.bing.com/")
                .setDownloader(chromeHeadlessDownloader)
                .addPipeline(bingImagePipeline).run();
    }

    @Override
    public void destroy() throws Exception {
        chromeHeadlessDownloader.close();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        chromeHeadlessDownloader = new ChromeHeadlessDownloader(environment.getProperty("webdriver.chrome.driver"));
        System.getProperties().setProperty("webdriver.edge.driver", environment.getProperty("webdriver.edge.driver"));
    }

}
